import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;


public class Download {
    /**
     * 下载文件方法
     * @param url 服务端地址
     * @param uuid uuid
     * @param path 本地存储路径
     * @return
     * @throws IOException
     */
    public String downloadFile(String url,String uuid,String path) throws IOException {

        url = url + "?uuid=" + uuid;
        URL connectionUrl = new URL(url);
        URLConnection urlConnection = connectionUrl.openConnection();
        HttpURLConnection connection = (HttpURLConnection) urlConnection;
        //将该连接的输入输出都设置为允许
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.setUseCaches(false);
        connection.setRequestMethod("GET");

        //长连接,建议服务器端保留连接，这样下次向同一个服务器发请求时可以走同一个连接
        connection.setRequestProperty("Connection", "Keep-Alive");
        //设置请求编码格式
        connection.setRequestProperty("Charset", "UTF-8");
        //连接阶段的设置结束

        connection.connect();
        if(connection.getResponseCode()!=200){
            return null;
        }
        else{
            InputStream in= connection.getInputStream();
            String type= connection.getHeaderField("type");
            String originalName= connection.getHeaderField("originalName");
            int length=in.available();
            OutputStream out=new FileOutputStream(path+originalName);
            byte[] buf=new byte[2048];
            int bytesRead=0;
            while ((bytesRead=in.read(buf))>0){
                out.write(buf,0,bytesRead);
            }
            return "download success";
        }
    }
}
